#ifndef SHARED_POINTER_H
#define SHARED_POINTER_H

#include "OSMutex.h"

template<typename T>
class SharedPointer
{
	class Owner;
public:
	explicit SharedPointer(T* p = NULL): mpOwner(new Owner(p)){ mpOwner->Inc(); }
	SharedPointer(const SharedPointer& sp): mpOwner(sp.mpOwner){mpOwner->Inc(); }
	SharedPointer& operator=(const SharedPointer& sp)
	{ mpOwner = sp.mpOwner; mpOwner->Inc(); return *this;}
	~SharedPointer(){ mpOwner->Dec(); }

	const T* operator->() const { return mpOwner->Object();}
	T* operator->() { return mpOwner->Object(); }

private:
	class Owner
	{
	public:
		Owner(T* inpObject)
		: mpObject(inpObject), mCount(0){}
		~Owner() {delete mpObject;}

		T* Object() {return mpObject;}
		void Inc()
		{
			OSMutex::Lock lock(mMutex);
			++mCount;
		}
		void Dec()
		{
			bool doDelete = false;
			{
				OSMutex::Lock lock(mMutex);
				doDelete = (--mCount == 0);
			}
			if(doDelete)
				delete this;
		}

	private:
		T*		mpObject;
		int		mCount;
		OSMutex mMutex;
	};

	Owner* mpOwner;
};


#endif